//需要在router/index.js中引入： import "./generateRoutes.js"

//使用require.context
//参数： 要搜索的目录。标记是否要搜索子目录。匹配文件的正则表达式
let files = require.context("../pages", true, /\.vue$/)
//console.log(files.keys());


let repeatRoutes = files.keys().map(path => {
    //需要将“./Home/Users/index.vue”转为“/Home/Users”
    let regExp = /(\/index\.vue|\.vue)$/
    //获取组件
    let com = files(path).default;
    //console.log(com,com.meta);

    path = path.replace(regExp, "").substring(1)
    //console.log(path);

    return {
        redirect: com.redirect ?? null,
        name: com.name ?? path.substring(1).split("/").join("-"),
        meta: com.meta ?? {},//路由原信息
        path: path.toLowerCase(),
        component: () => import("@/pages" + path)
    }
})
//console.log(repeatRoutes);
//export default repeatRoutes //扁平化的路由配置


//要把repeatRoutes转换为树形数据
const convertTree = (repeatRoutes) => {
    //每条数据添加id，如果是嵌套路由，添加pid

    let treeRoutes = []//声明一个空数组用于存放树形的routes配置

    repeatRoutes.forEach((route) => {
        //console.log(route);
        //将path作为当前对象的id
        let pathArr = route.path.substring(1).split('/')
        //console.log(pathArr);

        //给每个对象生成id
        route.id = pathArr.join('-')

        //如果数组中的长度大于1，则添加pid，parentId，数组中的最后一项去掉就是父级id了
        if (pathArr.length > 1) {
            let pidArr = [...pathArr]//浅拷贝
            pidArr.pop()
            route.pid = pidArr.join('-')
        }
        //console.log(route); 
    })

    //把平铺数据变为嵌套的树形数据
    repeatRoutes.forEach(route => {
        //找父级路由，id和pid相等的路由就是父路由
        let parent = repeatRoutes.find(v => v.id === route.pid)
        //console.log(parent);
        if (parent) {
            //当前的路由对象找到父节点了
            //判断父节点有没有children属性，没有就创建
            if (!parent.children) {
                parent.children = []
            }
            route.path = route.path.split('/').pop()
            parent.children.push(route)
        } else {
            //找不到父节点的路由对象就是根路由，直接添加到树形路由数据treeRoutes中
            treeRoutes.push(route)
        }
    })
    return treeRoutes
}
let result = convertTree(repeatRoutes)
//console.log(result);
 
export default result



